package com.scs.application.modules.dept.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.consts.GlobalConsts;
import com.scs.application.consts.SerialKeys;
import com.scs.application.core.entity.DataEntity;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.flow.FlowContext;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.DateUtils;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.core.utils.UtilCommon;
import com.scs.application.modules.base.mapper.DeptMapper;
import com.scs.application.modules.base.mapper.MatrMapper;
import com.scs.application.modules.dept.entity.OprtApply;
import com.scs.application.modules.dept.entity.OprtApplyItem;
import com.scs.application.modules.dept.mapper.OprtApplyItemMapper;
import com.scs.application.modules.dept.mapper.OprtApplyMapper;
import com.scs.application.modules.dept.service.OprtApplyItemService;
import com.scs.application.modules.dept.service.OprtApplyService;
import com.scs.application.modules.purchase.entity.Order;
import com.scs.application.modules.purchase.entity.OrderItem;
import com.scs.application.modules.purchase.enums.PoType;
import com.scs.application.modules.purchase.mapper.OrderItemMapper;
import com.scs.application.modules.purchase.mapper.OrderMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 */
@Service
public class OprtApplyServiceImpl extends BaseServiceImpl<OprtApplyMapper, OprtApply> implements OprtApplyService {

    @Resource
    private OprtApplyItemMapper oprtApplyItemMapper;

    @Resource
    OprtApplyItemService oprtApplyItemService;

    @Resource
    private MatrMapper matrMapper;

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;


    @Override
    public boolean saveOrUpdate(OprtApply entity) {
        if (StringUtils.isBlank(entity.getOprtApplyKey())) {
            if ("1".equals(entity.getOprtApplyType())) {
                entity.setOprtApplyKey(serialRuleAdapter.getSerialRuleService().generateCode(SerialKeys.OPRT_DEPT_APPLY_KEY));
            } else {
                entity.setOprtApplyKey(serialRuleAdapter.getSerialRuleService().generateCode(SerialKeys.OPRT_APPLY_KEY));
            }
        }
        return super.saveOrUpdate(entity);
    }

    @Override
    protected void beforeHandleFlowChange(FlowContext flowContext, OprtApply entity) {
        super.beforeHandleFlowChange(flowContext, entity);
        String buttonKey = flowContext.getButtonKey();
        // 提交审核，不允许空明细提交
        if ("submit".equalsIgnoreCase(buttonKey)) {
            List<OprtApplyItem> oprtApplyItems = oprtApplyItemMapper.selectList(Wrappers.<OprtApplyItem>query().eq("oprt_apply_id", flowContext.getBusId()));
            if (oprtApplyItems == null || oprtApplyItems.isEmpty()) {
                throw new BusinessException("请添加明细后提交");
            } else {
                oprtApplyItems.stream().filter(s -> "1".equals(s.getMatrType())).forEach(s -> {
                    List<OprtApplyItem> applyItems = oprtApplyItemMapper.selectList(Wrappers.<OprtApplyItem>query().eq("pack_apply_item_id", s.getId()));
                    if (applyItems == null || applyItems.isEmpty()) {
                        throw new BusinessException("包内没有耗材");
                    }
                });
            }
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeCascadeByIds(Collection<? extends Serializable> idList) {
        // applyItemMapper.delete(Wrappers.<ApplyItem>query().in("apply_id", idList));

        for (Serializable id : idList) {
            // 调用子表 执行库存解锁等逻辑
            List<OprtApplyItem> applyItems = oprtApplyItemService.list(Wrappers.<OprtApplyItem>query().eq("oprt_apply_id", id));
            if(applyItems == null || applyItems.size() <1) continue;
            oprtApplyItemService.removeCascadeByIds(applyItems.stream().map(o -> o.getId()).collect(Collectors.toList()));
        }
        return super.removeCascadeByIds(idList);
    }


    @Override
    protected void afterHandleFlowChange(FlowContext flowContext, OprtApply entity) {
        super.afterHandleFlowChange(flowContext, entity);

        if (!flowContext.isEndNode()) {
            return;
        }
        // 调用子表 执行库存解锁等逻辑
//        List<OprtApplyItem> applyItems = oprtApplyItemService.list(Wrappers.<OprtApplyItem>query().eq("oprt_apply_id", entity.getId()));
//        OprtApply entityDb = baseMapper.selectById(entity.getId());
//        //推送消息给运营管理员
//        CommonService.pushMessageRole("手术间备货申请:"+entityDb.getDeptName()+"--"+entityDb.getOprtApplyUser(),""+applyItems.size()+"条备货明细", "admin_yy");
        flowContext.setHandledMsg(StrUtil.format("审核通过，产生采购订单:{}",convertToOrders(entity).getBusKey()));
    }


    /***
     * @param entity
     * @Author: Tai
     * @date: 2024/6/3
     * @Description:  转换成采购订单
     */
    public Order convertToOrders(OprtApply entity) {
        String supplierId = entity.getSupplierId();

        List<OprtApplyItem> applyItems = oprtApplyItemService.list(Wrappers.<OprtApplyItem>query().eq("oprt_apply_id", entity.getId()).isNull("pack_id"));

        // 订单金额求和
        double sum = applyItems.stream().mapToDouble(o -> o.getAmount()).sum();
        // 根据一物一码和安全库存初分结算类型，调拨时再细分
        String orderCode = serialRuleAdapter.getSerialRuleService().generateCode(SerialKeys.PURCHASE_ORDER_KEY);
        String settlementType = GlobalConsts.SettlementType.usedSettlement;
        String remarkPre = UtilCommon.getStringPre(entity.getRemark(), 100);
        Order order = new Order();

        order.setBusKey(orderCode).setPurchaseType(null)
                .setSupplierId(supplierId)
                .setSupplierName(entity.getSupplierName())
                .setBusDate(new Date())
                .setBusUser(entity.getOprtApplyUser())

                // 采购科室
                .setDeptId(entity.getDeptId())
                .setDeptName(entity.getDeptName())

                // 需求科室
                .setDeptIdDemand(entity.getDeptId())
                .setDeptNameDemand(entity.getDeptName())
                .setFlagOmoc(true)
                .setSettlementType(settlementType)
                .setPoType(PoType.CONSIGNMENT.getValue())
                .setAmount(sum)
                .setFlagPushed(false)
                .setWarehouseId(entity.getWarehouseIdTo())
                .setWarehouseName(entity.getWarehouseNameTo())
                .setRefTable("dept_oprt_apply")
                .setRefId(entity.getId())
                .setRefKey(entity.getOprtApplyKey())
                .setRemark(String.format("备货单:%s,手术单号:%s,手术名称:%s", entity.getOprtApplyKey(),UtilCommon.getStr(entity.getOprtCode(),"无"),UtilCommon.getStr(entity.getOprtName(),"无")));
        ;
        order.setDateLates(DateUtils.addDays(new Date(), 3)).setPurchaseType(GlobalConsts.PO_PACKAGE);

        orderMapper.insert(order);

        for (OprtApplyItem item : applyItems) {
            OrderItem orderItem = new OrderItem();
            String[] ignoreFields = Arrays.asList(DataEntity.class.getDeclaredFields())
                    .stream().map(field -> field.getName()).collect(Collectors.toList()).toArray(new String[]{});
            BeanUtils.copyProperties(item, orderItem, ignoreFields);
            orderItem.setOrderId(order.getId())
                    .setRefId(item.getId())
                    .setRemark(item.getRemark())
            ;

            orderItemMapper.insert(orderItem);
        }

        return order;
    }
}
